<template>
	<div class="random">
		<div>
			<el-radio-group v-model="method" size="mini" @input="selectTurntable">
				<el-radio-button label="随机数"></el-radio-button>
				<el-radio-button label="随机字符"></el-radio-button>
				<el-radio-button label="自定义"></el-radio-button>
			</el-radio-group>
		</div>
		<table v-if="method=='随机数'">
			<tr>
				<td class="td1"><span>最小值</span></td>
				<td class="td2">
					<el-input v-model.number="randomMin" type="number" placeholder="请输入最小值" size="small"></el-input>
				</td>
			</tr>
			<tr>
				<td class="td1"><span>最大值</span></td>
				<td class="td2">
					<el-input v-model.number="randomMax" type="number" placeholder="请输入最大值" size="small"></el-input>
				</td>
			</tr>
			<tr>
				<td class="td1 top-align"><span>结果</span></td>
				<td class="td2">
					<el-table :data="randomNumResTab" :show-header="false" max-height="60">
					      <el-table-column prop="value" label="数据"></el-table-column>
					</el-table>
					<el-button type="primary" @click="randomNum()" size="small">随机</el-button>
				</td>
			</tr>
		</table>
		<table v-if="method=='随机字符'">
			<tr>
				<td class="td1"><span>多少位</span></td>
				<td class="td2">
					<el-input v-model.number="randomStrLen" placeholder="请输入要生成多少位字符" size="small"></el-input>
				</td>
			</tr>
			<tr>
				<td class="td1 top-align"><span>结果</span></td>
				<td class="td2">
					<el-table :data="randomStrResTab" :show-header="false" max-height="60">
					      <el-table-column prop="value" label="数据"></el-table-column>
					</el-table>
					<el-button type="primary" @click="randomStr()" size="small">随机</el-button>
				</td>
			</tr>
		</table>
		<div v-if="method=='自定义'" class="custom">
			<el-radio-group class="customGroup" v-model="custom" size="mini" @input="selectTurntable">
				<el-radio-button label="转盘"></el-radio-button>
				<el-radio-button label="自定义参数"></el-radio-button>
			</el-radio-group>
			<div v-if="custom=='转盘'">
				<div class="turntable">
				   <div class="route">
				     <canvas ref="canvas"></canvas>
				     <ul class="reward-list">
				     </ul>
				   </div>
				   <div class="point" @click="randomCustomData()"></div>
				 </div>
				<table>
					<tr>
						<td class="td1 top-align"><span>结果</span></td>
						<td class="td2">
							<el-table :data="randomCusResTab" :show-header="false" max-height="60">
							      <el-table-column prop="value" label="数据"></el-table-column>
							</el-table>
						</td>
					</tr>
				</table>
			</div>
			<div v-if="custom=='自定义参数'">
				<el-input type="textarea" :rows="11" placeholder="请输入内容" v-model="customText" @change="setCustomTableData()"></el-input>
				
				<div class="configuration">
					<div>
						<span>结果是否弹出提示框</span>
					</div>
					<div>
						<el-switch v-model="popupTip"></el-switch>
					</div>
				</div>
				
				<el-table
					class="customTableData"
				    :data="customTableData"
					:show-header="false"
				    row-key="id"
				    border
				    default-expand-all
					:span-method="handleSpanMethod"
				    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
				    <el-table-column prop="key" width="180">
				    </el-table-column>
					<el-table-column>
						<template slot-scope="scope">
							<el-input 
								v-model="scope.row.value" 
								maxlength="14"
								placeholder="请输入内容" 
								size="small" 
								:readonly="scope.row.key=='上传图片'"
								@input="handleValueChange(scope.row, scope.$index)"
								>
							</el-input>
						</template>
					</el-table-column>
					<el-table-column>
						<template slot-scope="scope" v-if="scope.row.key == '上传图片'">
							<el-upload
								ref="upload"
								action
								:show-file-list = "false"
								:http-request = "param => uploadFile(param,scope.row)"
							>
								<el-button type="primary" size="mini" title="上存文件,得到文件的base64编码">上存文件</el-button>
							</el-upload>
						</template>
					</el-table-column>
				  </el-table>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				method:"随机数",
				randomMin:0,
				randomMax:10,
				randomNumRes:[],
				randomStrLen:0,
				randomStrRes:[],
				custom:"转盘",
				customText:"做一个一字马动作\n头向下转8圈然后走一条直线\n边摸自己大腿边说'真像萝卜'\n在自己的肚子上画个心\n含着手指表现出呆萌的样子\n给自己画上性感的小胡子\n用头在墙上写一个大大的'服'字\n用活泼的表情唱一首儿歌\n在自己的面上任意位置画三颗痣\n用透明胶贴在小腿上然后撕掉",
				customTableData:[],
				randomCusRes:[],
				canvasSize:500,
				startDraw:true,
				popupTip:false,
			}
		},
		computed:{
			randomNumResTab() {
				return this.randomNumRes.map((value) => ({ value }));
			},
			randomStrResTab() {
				return this.randomStrRes.map((value) => ({ value }));
			},
			randomCusResTab() {
				return this.randomCusRes.map((value) => ({ value }));
			},
			// customTableData(){
			// 	const datas = this.customText.split( /[,\n]/g);
			// 	let tableData=[];
			// 	for(let i=1;i<=datas.length;i++){
			// 		const obj = {
			// 		  id: i,
			// 		  key: '标题',
			// 		  value: datas[i-1],
			// 		  children: [{
			// 			  id: i*100+10,
			// 			  key: '备注',
			// 			  value: '备注信息'
			// 			// }, {
			// 			//   id: i*100+20,
			// 			//   key: '奖品份数',
			// 			//   value: '1'
			// 			}, {
			// 			  id: i*100+30,
			// 			  key: '中奖概率',
			// 			  value: this.approach(1/datas.length,100)
			// 			}, {
			// 			  id: i*100+40,
			// 			  key: '上传图片',
			// 			  // value: 'https://myjavaweb.oss-cn-guangzhou.aliyuncs.com/lmjresume/img/192.png',
			// 			  value: ''
			// 			}]
			// 		}
			// 		tableData.push(obj);
			// 	}
			// 	return tableData;
			// }
		},
		methods: {
			randomNum(){
				//生成0到1之间的随机数:Math.random();
				var result = Math.floor(Math.random() * (this.randomMax - this.randomMin + 1)) + this.randomMin;
				this.randomNumRes.unshift(result);
			},
			randomStr(){
				let result = '';
				const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				const charactersLength = characters.length;
				
				for (let i = 0; i < this.randomStrLen; i++) {
					result += characters.charAt(Math.floor(Math.random() * charactersLength));
				}
				
				this.randomStrRes.unshift(result);
			},
			// 绘制转盘内容
			drawGird() {
				const size = this.canvasSize;
				// console.log(this.customTableData)
				const datas = this.customTableData;
				const color = ["#e1f3d8", "#faecd8", "#fde2e2"];
				//数据个数
				const length = datas.length;
				//每一份角度
				const angle = (Math.PI * 2) / length;
				//起始角度
				const startAngle = -Math.PI/2;
				
				const canvas = this.$refs.canvas
				canvas.width = size; // 设置宽度
				canvas.height = size; // 设置高度
				const ctx = canvas.getContext("2d");
				ctx.clearRect(0, 0, size, size);
				ctx.beginPath();
				ctx.arc(size/2, size/2, size/2-1, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.closePath();
						
				for(let i=0;i<length;i++){
					ctx.beginPath();
					//移动到中心点
					ctx.moveTo(size/2, size/2);
					//画每一个扇形
					ctx.arc(size/2, size/2, size/2-1, startAngle + angle * i, startAngle + angle * (i + 1));
					//判断是否为最后一个格子
					if(i===length-1 && i%3==0){
						ctx.fillStyle = color[1]
					}else{
						ctx.fillStyle = color[i % 3]
					}
					//填充颜色
					ctx.fill()
					ctx.stroke();
					ctx.closePath();
					
					//绘制弧形
					if(datas[i].children[2].value==""){
						ctx.save();
						// 将原点移至矩形中心
						ctx.translate(size/2, size/2);
						// 旋转图形(每份角度 + 每份角度的一半)
						ctx.rotate(angle*i + angle/2);
						ctx.fillStyle = "rgba(0,0,0,1)"
						// 设置字体样式
						ctx.font = `bold ${size/20}px Arial`;
						ctx.textAlign = "center";
						ctx.textBaseline = "middle";
						// 设置文本颜色
						ctx.fillStyle = "blue";
						// 写字
						if(datas[i].value.length>14){
							ctx.fillText(datas[i].value.substr(0,5), 0, -size/2.3);
							ctx.fillText(datas[i].value.substr(5,4), 0, -size/2.7);
							ctx.fillText(datas[i].value.substr(9,3), 0, -size/3.3);
							ctx.fillText(datas[i].value.substr(12,2), 0, -size/4.2);
							ctx.fillText(datas[i].value.substr(14,1), 0, -size/5.7);
						}else if(datas[i].value.length>12){
							ctx.fillText(datas[i].value.substr(0,5), 0, -size/2.3);
							ctx.fillText(datas[i].value.substr(5,4), 0, -size/2.7);
							ctx.fillText(datas[i].value.substr(9,3), 0, -size/3.3);
							ctx.fillText(datas[i].value.substr(12,2), 0, -size/4.2);
						}else if(datas[i].value.length>9){
							ctx.fillText(datas[i].value.substr(0,5), 0, -size/2.3);
							ctx.fillText(datas[i].value.substr(5,4), 0, -size/2.7);
							ctx.fillText(datas[i].value.substr(9,3), 0, -size/3.3);
						}else if(datas[i].value.length>5){
							ctx.fillText(datas[i].value.substr(0,5), 0, -size/2.3);
							ctx.fillText(datas[i].value.substr(5,4), 0, -size/2.7);
						}else{
							ctx.fillText(datas[i].value, 0, -size/2.3);
						}
						// 恢复画布状态
						ctx.restore(); 
					}else{
						var newImg = new Image()
						newImg.src = datas[i].children[2].value
						newImg.onload = ()=> {
							ctx.save();
							// 将原点移至矩形中心
							ctx.translate(size/2, size/2);
							// 旋转图形(每份角度 + 每份角度的一半)
							ctx.rotate(angle*i + angle/2);
							ctx.fillStyle = "rgba(0,0,0,1)"
							// 设置字体样式
							ctx.font = `bold ${size/23}px Arial`;
							ctx.textAlign = "center";
							ctx.textBaseline = "middle";
							// 设置文本颜色
							ctx.fillStyle = "blue";
							// 写字
							if(datas[i].value.length>7){
								ctx.fillText(datas[i].value.substr(0,4), 0, -size/3.3);
								ctx.fillText(datas[i].value.substr(4,3), 0, -size/4.1);
								ctx.fillText(datas[i].value.substr(7,2), 0, -size/5.3);
							}else if(datas[i].value.length>4){
								ctx.fillText(datas[i].value.substr(0,4), 0, -size/3.3);
								ctx.fillText(datas[i].value.substr(4,3), 0, -size/4.1);
							}else{
								ctx.fillText(datas[i].value, 0, -size/3.3);
							}
							// 画图
							ctx.drawImage(newImg,-size/10/2,-size/2.17,size/10,size/10)
							// 恢复画布状态
							ctx.restore(); 
						}
					}
				}
			},
			// 旋转转盘
			randomCustomData() {
				if(this.startDraw){
					this.startDraw = false;
					const length = this.customTableData.length;
					// 计算中奖概率
					let which = -1;
					for(let data of this.customTableData){
						if(data.children[1].value>=1)which=data.id;
					}
					// 随机中奖
					which = which == -1 ? this.random(length) : which;
					let el = document.querySelector(".route");
					//旋转角度 = 固定圈数 - index * (每一份角度) - 中心偏移
					let rAngle = which * (360 / length) - 180 / length;
					el.style["transform"] = `rotate(${36000 - rAngle}deg)`;
					el.style["transition"] = "transform 3s cubic-bezier(0, 1, 0.2, 1)";
					setTimeout(() => {
						const data = this.customTableData[which-1];
						this.randomCusRes.unshift(data.value);
						el.style["transform"] = `rotate(${-rAngle}deg)`;
						el.style["transition"] = "none";
						this.startDraw = true;
						if(this.popupTip){
							this.$alert(data.children[0].value, data.value);
						}
					}, 3000);
				}
			},
			random(num) {
				return Math.floor(Math.random() * num) + 1;
			},
			selectTurntable(){
				if(this.method=="自定义" && this.custom=="转盘"){
					 this.$nextTick(() => {
						// 在页面渲染完成后执行
						this.drawGird();
					});
				}
			},
			handleResize() {
				if(window.innerWidth<=767){
					this.canvasSize = 350
				}else{
					this.canvasSize = 500
				}
			},
			uploadFile(param, val){
				let file = param.file;
				const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
				const isJPG = typeArr.indexOf(file.type) !== -1;
				const isLt3M = file.size / 1024 / 1024 < 3;
				if (!isJPG) {
					this.$message.error('只能是图片!');
					this.$refs.upload.clearFiles();
					this.files = null;
					return;
				}
				if (!isLt3M) {
					this.$message.error('上传图片大小不能超过 3MB!');
					this.$refs.upload.clearFiles();
					this.files = null;
					return;
				}
				let reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload=()=>{
					const base64 = reader.result.split(",");
					const mediaType = base64[0].match(/^data:(.+);base64$/);
					const Blob = this.dataURLtoBlob(base64[1],mediaType[1]);
					val.value = URL.createObjectURL(Blob);
				}
			},
			dataURLtoBlob(base64Str, mimeTypeStr) {
				var bstr = atob(base64Str);
				var n = bstr.length;
				var u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], { type: mimeTypeStr });
			},
			handleSpanMethod({ row, column, rowIndex, columnIndex }) {
				if(row.key!=="上传图片"){
					//第二列
					if(columnIndex===1){
						//合并1行2列
						return [1,2];
					}
				}
			},
			handleValueChange(row, index) {
				if(row.key=="备注"){
					console.log("备注")
				}
				if(row.key=="概率"){
					console.log("概率")
					// 手动触发 customTableData 的重新计算
					// this.customTableData = [...this.customTableData];
				}
			},
			setCustomTableData(){
				const datas = this.customText.split( /[,\n]/g);
				let tableData=[];
				for(let i=1;i<=datas.length;i++){
					const obj = {
					  id: i,
					  key: '标题',
					  value: datas[i-1],
					  children: [{
						  id: i*100+10,
						  key: '备注',
						  value: '备注信息'
						}, {
						  id: i*100+30,
						  key: '概率',
						  value: this.approach(1/datas.length,100)
						}, {
						  id: i*100+40,
						  key: '上传图片',
						  // value: 'https://myjavaweb.oss-cn-guangzhou.aliyuncs.com/lmjresume/img/192.png',
						  value: ''
						}]
					}
					tableData.push(obj);
				}
				this.customTableData = tableData;
			},
		},
		created() {
			this.setCustomTableData();
			this.handleResize();
		},
		mounted(){
			if(this.method=="自定义" && this.custom=="转盘"){
				this.drawGird();
				window.addEventListener('resize', this.handleResize);
			}
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.handleResize);
		},
	}
</script>

<style scoped>
	.random{
		width: 100%; 
		height: 100%;
		text-align: left;
	}
	.random>div{
		margin-bottom: 10px;
	}
	.random table{
		table-layout: fixed;
		font-size: 16px;
	}
	.random table tr td {
		height: 33px;
		text-align: left;
		word-wrap: break-word;
		word-break: break-all;
	}
	.el-table{
		background-color: #e5e5e5;
		height: 60px;
	}
	.el-table >>> .el-table__row td{
		padding:0;
	}
	.el-table >>> .el-table__row div{
		background-color: #e5e5e5;
	}
	.top-align{
		line-height: 33px;
		vertical-align: top;
	}
	.customGroup{
		margin-bottom: 10px;
	}
	
	.turntable {
		margin: 10px 0;
		width: 500px;
		height: 500px;
		background-color: gray;
		border-radius: 50%;
		position: relative;
	}
	.route {
		width: 100%;
		height: 100%;
		position: relative;
	}
	.point {
		width: 80px;
		height: 80px;
		position: absolute;
		top: calc(50% - 40px);
		left: calc(50% - 40px);
		background-color: red;
		border-radius: 50%;
	}
	.point::after {
		position: absolute;
		content: "";
		width:0;
		height:0;
		top:calc(50% - 80px);
		left:calc(50% - 15px); 
		border-left: 15px solid transparent;
		border-right: 15px solid transparent;
		border-bottom: 60px solid red;
	}
	
	.configuration{
		margin-top: 10px;
		font-size: 16px;
		display: table;
		width: 100%;
	}
	.configuration div:nth-of-type(1){
		display: table-cell;
		padding-left: 10px;
		width: 170px;
		vertical-align: middle;
	}
	.configuration div:nth-of-type(2){
		display: table-cell;
	}
	
	.customTableData{
		margin-top: 10px;
		background-color: #ffffff;
		height: 60px;
		width: 100%;
		height: 100%;
		margin-bottom: 20px;
	}
	.customTableData >>> .el-table__row div{
		background-color: #ffffff;
	}
	.customTableData >>> .cell{
		padding: 0;
	}
	.el-input >>> .el-input__inner[readonly]{
		background-color: #e5e5e5;
	}
	
	@media screen and (min-width: 1200px){
		.td1{
			width: 110px;
		}
		.td2{
			width: 800px;
		}
	}
	@media screen and (max-width: 1200px){
		.td1{
			width: 110px;
		}		
		.td2{
			width: 450px;
		}
	}
	@media screen and (max-width: 767px){
		.td1{
			width: 75px;
		}
		.td2{
			width: 275px;
			font-size: 14px;
		}
		.turntable {
			margin: 10px auto;
			width: 350px;
			height: 350px;
		}
	}
</style>